﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Collections;
using System.Web.Security;
using Beeldbankmvc.Models;
using System.Web.Mvc;
using System.Configuration;
using Beeldbankmvc.Helpers;
using System.IO;

namespace Beeldbankmvc.Code
{
    public class AppHelper
    {
        //
        // Random funcion only works when initialised once
        //
        // url: http://www.velocityreviews.com/forums/t84217-random-not-really-random.html
        //
        private static int TheSeed = (int)DateTime.Now.Ticks;
        private static Random r = new Random(TheSeed);
        
        public static string CSSRotatingBackground()
        {
            if (ConfigurationManager.AppSettings["publicationName"].Equals("RVDR"))
            {
                var Url = new UrlHelper(((MvcHandler)HttpContext.Current.Handler).RequestContext);
                int randomNumber = r.Next(8);

                return "<link href=\"" + AppHelper.getContent("~/[Content]/css/Background" + randomNumber + ".css") + "\" id=\"Background" + randomNumber + "\" rel=\"stylesheet\" " +
                        "type=\"text/css\"  media=\"screen\" />";
            }
            else
                return "";
        }

        public static string linkLoginOrWelcome()
        {
            string linkToReturn = "";

            var Url = new UrlHelper(((MvcHandler)HttpContext.Current.Handler).RequestContext);

            MembershipUser currentUser = Membership.GetUser();
            if (currentUser == null)
            {
                linkToReturn = "<a href=\"" + AppHelper.getContent("~/Account/LogOn") + "\" title=\"Account\" tabindex=\"5\">Inloggen</a>";
                linkToReturn += "<a href=\"" + AppHelper.getContent("~/Account/Register") + "\" title=\"Account\" tabindex=\"6\">Registreren</a>";
            }
            else
            {
                linkToReturn = "<a href=\"" + AppHelper.getContent("~/Account/EditAccount") + "\" title=\"Account\" tabindex=\"5\">" +
                                "Welkom, " + currentUser.UserName + "</a>";
                linkToReturn += "<a href=\"" + AppHelper.getContent("~/Account/LogOff") + "\" title=\"Account\" tabindex=\"6\">Uitloggen</a>";

            }
            return linkToReturn;
        }


        public static string shoppingCartItems()
        {
            MembershipUser currentUser = Membership.GetUser();
            if (currentUser == null)
            {
                return "";
            }
            else
            {
                var cart = ShoppingCart.GetCart(new System.Web.HttpContextWrapper(HttpContext.Current));
                if (cart != null)
                {
                    return cart.GetCount().ToString();
                }
                else
                {
                    return "0";
                }
            }
        }


        public static string convertToUrlTitle(String omschrijving, int itemId)
        {
            string regex = "[^^A-Za-z0-9]";
            System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline)
                        | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);

            string retVal = "";

            if (!String.IsNullOrEmpty(omschrijving))
            {
                if (omschrijving.IndexOf('.') < 30)
                {
                    System.StringSplitOptions splitOptions = System.StringSplitOptions.RemoveEmptyEntries;
                    String[] newLine = { "\n" };

                    retVal = reg.Replace(StripHTMLTags(omschrijving.Replace("<br />", " ")).Replace("GPS", "\n").Replace("\r", "").Replace(":", ".").Replace("  ", " ").Split(newLine, splitOptions)[0], " ").Trim(' ');
                }
                else
                    retVal = reg.Replace(StripHTMLTags(omschrijving.Replace("<br />", " ")).Replace("GPS", ".").Replace("\n", ".").Replace("\r", "").Replace("\n", ".").Replace(":", ".").Replace("  ", " ").Split('.')[0], "_").Trim('_');
            }
            else
                retVal = "Geen_omschrijving";

            // if there is no new line or dot to split on, hard split om 170 characters, the total URL length can be no more then 260 characters
            if (retVal.Length > 170)
                retVal = retVal.Substring(0, 170);

            retVal = retVal + "_" + itemId;

            return retVal;
        }

        // This function is currently unused since it causes a combination of http and https elements on one page
        public static string convertOmschrijvingToGoogleMap(String omschrijving)
        {
            string retVal = "";
            if (omschrijving.Contains("GPS</abbr>:</strong> "))
            {
                int startLokatieString = omschrijving.IndexOf("GPS</abbr>:</strong> ") + 21;
                int eindLokatieString = omschrijving.Substring(startLokatieString, omschrijving.Length - startLokatieString - 1).IndexOf("<br />");
                string LokatieString = omschrijving.Substring(startLokatieString, eindLokatieString - 1).Replace(" ", "+");
                // Static Google map image
                //retVal = "<br /><img alt='Detail lokatie op de kaart van Nederland waar de foto genomen is.' src='http://maps.google.com/maps/api/staticmap?center=" + LokatieString + "&amp;zoom=14&amp;size=300x200&amp;maptype=roadmap&&sensor=false&amp;markers=color:yellow|label:R|" + LokatieString + "' />";
                //retVal = "<br /><img alt='Detail lokatie op de kaart van Nederland waar de foto genomen is.' src='https://maps.google.com/maps/api/staticmap?center=" + LokatieString + "&amp;zoom=14&amp;size=300x200&amp;maptype=roadmap&&sensor=false&amp;markers=color:yellow|label:R|" + LokatieString + "' />";
                
                // Dynamic Google map include
                retVal = "<br /><iframe title='Detail lokatie op de kaart van Nederland waar de foto genomen is.' width='216' height='216' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='https://maps.google.com/?ie=UTF8&amp;q=" + LokatieString + "&amp;t=h&amp;z=14&amp;markers=size:mid|color:0xFFFF00||&amp;output=embed'></iframe>";
            }
            return retVal;
        }

        public static string convertHtmlStringToAltTag(int mediaObjectId)
        {
            MediaObjectRepository mediaObjectRepository = new MediaObjectRepository();
            return convertHtmlStringToAltTag(mediaObjectRepository.FindOne(mediaObjectId));
        }

        public static string convertHtmlStringToAltTag(BEELDBANK_MEDIAOBJECT mediaObject)
        {
            if (!String.IsNullOrEmpty(mediaObject.AltTekst))
                return mediaObject.AltTekst;

            string omschrijving = mediaObject.Omschrijving;

            string regex = "[^^A-Za-z0-9]";
            System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace
                | System.Text.RegularExpressions.RegexOptions.Multiline)
                | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);

            string retVal = "";
           
            int lokPeriod = -1;
            int increment = 50;
            bool stop = false;
            if (!String.IsNullOrEmpty(omschrijving))
            {
                while ((lokPeriod <= 0) && !stop)
                {
                    if (omschrijving.Length > increment)
                        lokPeriod = omschrijving.Substring(0, increment).LastIndexOf('.');

                    if ((omschrijving.Length > increment) && (lokPeriod < increment) && (lokPeriod > 0))
                        stop = true;
                    else
                        if (omschrijving.Length <= increment)
                            stop = true;
                    increment += 30;
                }
                if (lokPeriod > 0)
                    omschrijving = omschrijving.Substring(0, lokPeriod + 1);

                if (omschrijving.LastIndexOf('.') < 50)
                {
                    String[] newLine = { "\n" };
                    //retVal = reg.Replace(StripHTMLTags(omschrijving.Replace("<br />", " ")).Replace("GPS", "\n").Replace("\r", "").Split(newLine, splitOptions)[0], " ").Trim(' ');
                    retVal = StripHTMLTags(omschrijving.Replace("<br />", " ")).Replace("GPS", "\n").Replace("\r", "");
                }
                else
                    //retVal = reg.Replace(StripHTMLTags(omschrijving.Replace("<br />", " ")).Replace("GPS", ".").Replace("\r", "").Replace("\n", ".").Split('.')[0], " ").Trim(' ');
                    retVal = StripHTMLTags(omschrijving.Replace("<br />", " ")).Replace("GPS", ".").Replace("\r", "").Replace("\n", ".");
            }
            else
                retVal = "";

            return retVal.Replace("  ", " ").Replace(" '", " ").Replace("; ", " ").Replace("  ", " ");
        }

        /// <summary>
        /// Remove HTML tags from string using char array.
        /// </summary>
        public static string StripHTMLTags(string source)
        {
            if (source == null)
            {
                return "";
            }

            char[] array = new char[source.Length];
            int arrayIndex = 0;
            bool inside = false;

            for (int i = 0; i < source.Length; i++)
            {
                char let = source[i];
                if (let == '<')
                {
                    inside = true;
                    continue;
                }
                if (let == '>')
                {
                    inside = false;
                    continue;
                }
                if (!inside)
                {
                    array[arrayIndex] = let;
                    arrayIndex++;
                }
            }
            return new string(array, 0, arrayIndex);
        }

        public static string filterOutSpecialCharacters(String formattedString)
        {
            string regex = "[^^A-Za-z0-9]";
            System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline)
                        | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);

            return reg.Replace(formattedString, " ");
        }

        public static string filterOutHTML(String htmlText)
        {
            // Changed from empty string to space character
            return filterOutHTML(htmlText, " ");
        }

        public static string filterOutHTML(String htmlText, String replace)
        {
            string regex = "(?></?\\w+)(?>(?:[^>\'\"\"]+|\'[^\']*\'|\"\"[^\"\"]*\"\")*)>";
            System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline)
                        | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);

            String retVal = reg.Replace(htmlText, replace);

            return retVal;
        }

        public static string getContent(string contentUri)
        {
            var Url = new UrlHelper(((MvcHandler)HttpContext.Current.Handler).RequestContext);

            if(contentUri.Contains("[Content]"))
                contentUri = contentUri.Replace("[Content]", ConfigurationManager.AppSettings["contentFolderName"]);

            contentUri = Url.Content(contentUri);

            return contentUri;
        }

        public static String getAvailableVideoFileTypes(int? MediaObjectFileId)
        {
            HashSet<string> availableFileExtentions = new HashSet<string>();

            // Determine first part of the filename
            int mapNumber = MediaObjectFileId.Value / Convert.ToInt32(ConfigurationManager.AppSettings["MaxFotosInDirectory"]);
            // Determine first part of the filename
            string path = "";
            path = ConfigurationManager.AppSettings["VideoArchive"] + "\\" + mapNumber.ToString();
            // Check if directory exists
            if (Directory.Exists(path))
            {
                // Process the list of files found in the directory.

                // example path E:\Development\VS.NET\Beeldbank\Data\video\2920

                string[] fileEntries = Directory.GetFiles(path);
                foreach (string file in fileEntries)
                {
                    String onlyfile = file.Substring(file.LastIndexOf('\\') + 1);

                    if (onlyfile.Split('.')[0].Equals(MediaObjectFileId.Value.ToString()))
                    {
                        availableFileExtentions.Add(onlyfile.Split('.')[1]); //get the extention
                    }
                }
            }

            string availableFileTypes = ConfigurationManager.AppSettings["alwaysAvailableVideoFileTypes"];
            foreach (String fileType in availableFileExtentions)
            {
                availableFileTypes += "," + fileType;
            }
        

            return availableFileTypes;
        }

        public static String getGPSLink(double? latitude, double? longitude, int? hoogte, DateTime? datecreated, int? googlezoom)
        {
            if ((latitude.HasValue) && (longitude.HasValue))
            {
                BEELDBANK_MEDIAOBJECT tmpMediaObject = new BEELDBANK_MEDIAOBJECT();
                tmpMediaObject.Latitude = latitude.Value;
                tmpMediaObject.Longitude = longitude.Value;
                if (hoogte.HasValue) tmpMediaObject.Hoogte = hoogte.Value;
                if (datecreated.HasValue) tmpMediaObject.Datum_Realisatie = datecreated.Value;
                if (googlezoom.HasValue) tmpMediaObject.GoogleZoom = googlezoom.Value;
                return getGPSLink(tmpMediaObject);
            }
            else
                return "";
        }

        public static String getGPSLink(BEELDBANK_MEDIAOBJECT MediaObject)
        {
            if (MediaObject.Latitude.HasValue)
            {
                try
                {
                    string Latitude = MediaObject.Latitude.ToString().Replace(",", ".");
                    string Longitude = MediaObject.Longitude.ToString().Replace(",", ".");

                    // Conversion from decimal to degrees
                    string LatDeg = Convert.ToInt32(MediaObject.Latitude).ToString() + " ";
                    string LatMin = Convert.ToInt32((MediaObject.Latitude % 1) * 60).ToString() + "' ";
                    string LatSec = Convert.ToInt32((((MediaObject.Latitude % 1) * 60) % 1) * 60).ToString() + "\" N, ";
                    string LongDeg = Convert.ToInt32(MediaObject.Longitude).ToString() + " ";
                    string LongMin = Convert.ToInt32((MediaObject.Longitude % 1) * 60).ToString() + "' ";
                    string LongSec = Convert.ToInt32((((MediaObject.Longitude % 1) * 60) % 1) * 60).ToString() + "\" E";

                    string Hoogte = "";
                    if (MediaObject.Hoogte.HasValue)
                        Hoogte = "Hoogte: " + MediaObject.Hoogte.ToString() + " meter<br />";
                    string Datum = "";
                    if (MediaObject.Datum_Realisatie.ToString() != "01-01-1900")
                        Datum = "Datum: " + String.Format("{0:d}", MediaObject.Datum_Realisatie) + "<br />";
                    string Zoom = "8";
                    if (MediaObject.GoogleZoom.HasValue)
                        Zoom = MediaObject.GoogleZoom.ToString();

                    string tmpString = "GPS "
                        + "<a title='Externe doorverwijzing naar de lokatie op Google maps' href='http://maps.google.com/maps?f=q&amp;hl=nl&amp;z=" + Zoom + "&amp;q=" + Latitude + "," + Longitude + "' >" + LatDeg + LatMin + LatSec + LongDeg + LongMin + LongSec + "</a><br />" + Hoogte + Datum;

                    return tmpString;
                }
                catch
                {
                    return "";
                }
            }
            else
                return "";
        }
    }
}